package com.cloudeye.logtest.base;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by lafangyuan on 2021/1/27.
 */
public class HashMapCode {

    public static void main(String[] args) {


//        System.out.println(ma);
//        System.out.println(mb);
//        String ra = map.get(a);
//        System.out.println(ra);
//        String rb = map.get(b);
//        System.out.println(rb);
//        new HashMapCode().testEqualsHash();
        new HashMapCode().testHashCode();;
    }
//96355

    public void testHashCode() {
        Code a = new Code("a", "a");
        Code b = new Code("b", "b");
        Map<Code, String> map = new HashMap<>();
        String ma = map.put(a, "a");
        String mb = map.put(b, "b");
        System.out.println(map.size());
        System.out.println(map.get(a));
    }

    /**
     * hash对n取模和 hash&(n-1)效果是一样的,但是与运算的性能要比取模高
     */
    public void testEqualsHash(){
        int n = 16;
        String key = "abcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxasaaaaaaaaaaaaaaaaaaaaadfadfadsfadfadfwefadfadfadfafdadffadffadfsafe";
        long start = System.currentTimeMillis();
        System.out.println(key.hashCode()%n);
        long end1 = System.currentTimeMillis();
        System.out.println("取模耗时："+(end1-start));
        System.out.println(key.hashCode()&(n-1));
        long end2 = System.currentTimeMillis();
        System.out.println("取模耗时："+(end2-end1));

    }

    /**
     * hashMap的方法
     * @param key
     * @return
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    static class Code{
        String name;
        String data;

        public Code(String name, String data) {
            this.name = name;
            this.data = data;
        }

        public Code() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Code code = (Code) o;
            return getName().equals(code.getName()) &&
                    getData().equals(code.getData());
        }

        @Override
        public int hashCode() {
            return 1;
        }
    }
}
